class UtilsC {
  getUserFromIP(ipuser_list, ip) {
    return ipuser_list.map(function (ipuser, index) {
      if (ipuser.ip == ip) {
        return ipuser.user;
      }
    });
  }

  formatHTML(value) {
    //value = value.replace(/。/g, "。<br />")
    //value = value.replace(//g, "<br />")
    //value = value.replace(/；/g, "；<br />")
    //value = value.replace(/:/g, ":<br />")
    //value = value.replace(/：/g, "：<br />")
    value = value.replace(/\n/g, "<br />");
    //value = value.replace(/\r/g, "<br />")

    return value;
  }

  formatText(value) {
    value = value.replace(/<br \/>/g, "\n");
    return value;
  }
}
const utils = new UtilsC();

class WeeklyContentRender extends React.Component {
  componentWillReceiveProps() {
    this.state = {
      value: this.props.weekly.body != null ? this.props.weekly.body : ""
    };
  }

  HTML() {
    const that = this;
    var body_replace = utils.formatHTML(this.props.weekly.body);

    const body_split = body_replace.split("<br />");
    return body_split.map(function (body, index) {
      return <p>{body}</p>;
    });
  }

  onChangeValue = e => {
    this.setState({
      value: e.target.value
    });
  };

  Body() {
    if (this.props.weekly_editing) {
      return (
        <textarea
          rows="30"
          onChange={this.onChangeValue}
          value={this.state.value}
        ></textarea>
      );
    }
    return this.HTML();
  }

  AddButton() {
    if (
      this.props.weeknum_of_year != this.props.weekly_max_num &&
      !this.props.weekly_editing
    ) {
      return (
        <button
          className="button-success pure-button"
          onClick={this.props.app.WeeklyContentAddPop.bind(this.props.app)}
        >
          提交第{this.props.weeknum_of_year}周周报
        </button>
      );
    }
  }

  SendButton() {
    if (this.state.value != "") {
      return (
        <button
          className="button-success pure-button"
          onClick={this.props.app.WeeklyContentSendPop.bind(
            this.props.app,
            this.props.weekly,
            this.state.value
          )}
        >
          确认
        </button>
      );
    } else {
      return (
        <button
          className="button-success pure-button"
          onClick={this.props.app.WeeklyContentSendPop.bind(
            this.props.app,
            this.props.weekly,
            this.state.value
          )}
          disabled
        >
          确认
        </button>
      );
    }
  }

  CenterButton() {
    return (
      <button
        className="button-error pure-button"
        onClick={this.props.app.WeeklyContentCenterPop.bind(this.props.app)}
      >
        取消
      </button>
    );
  }

  EditButton() {
    if (this.props.weekly.weeknum >= this.props.weeknum_of_year) {
      return (
        <button
          className="button-warning pure-button"
          onClick={this.props.app.WeeklyContentEditPop.bind(
            this.props.app,
            this.props.weekly,
            this.state.value
          )}
        >
          修改
        </button>
      );
    }
  }

  ControlButton() {
    if (this.props.wait_for_weekly) {
      return (
        <div id="loadingWrap2">
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
        </div>
      );
    }

    if (!this.props.wait_for_weekly) {
      if (this.props.weekly_editing) {
        return (
          <p>
            {this.SendButton()}
            &nbsp;&nbsp;
            {this.CenterButton()}
          </p>
        );
      } else {
        return (
          <p>
            {this.AddButton()}
            {this.EditButton()}
          </p>
        );
      }
    }
  }

  Subtitle() {
    if (this.props.weekly.ip != "" && this.props.weekly.updatetime != "") {
      return (
        <div>
          From{" "}
          <a>
            {utils.getUserFromIP(this.props.ipuser_list, this.props.weekly.ip)}(
            {this.props.weekly.ip})
          </a>{" "}
          at <span>{this.props.weekly.updatetime}</span>
        </div>
      );
    }
  }

  render() {
    if (this.props.weekly == "") {
      return <div></div>;
    }

    return (
      <div id="main" className="pure-u-1">
        <div className="email-content">
          <div className="email-content-header pure-g">
            <div className="pure-u-1-2">
              <h1 className="email-content-title">
                2019年第{this.props.weekly.weeknum}周
              </h1>
              <p className="email-content-subtitle">{this.Subtitle()}</p>
            </div>
            <div class="email-content-controls pure-u-1-2">
              {this.ControlButton()}
            </div>
          </div>
          <div className="email-content-body">{this.Body()}</div>
        </div>
      </div>
    );
  }
}

class WeeklyListRender extends React.Component {
  constructor(props) {
    super(props);
  }

  Title(weekly) {
    return (
      <div className="pure-u-3-4">
        <h5 className="email-name">
          提交人：{utils.getUserFromIP(this.props.ipuser_list, weekly.ip)}
        </h5>
        <h4 className="email-subject">2019年第{weekly.weeknum}周</h4>
        <p className="email-desc">{weekly.body.substr(0, 30)} ...</p>
      </div>
    );
  }

  Item(weekly) {
    if (weekly.id == this.props.select_weekly_id) {
      return (
        <div className="email-item email-item-selected pure-g">
          {this.Title(weekly, this.props.ipuser_list)}
        </div>
      );
    } else {
      return (
        <div className="email-item email-item-unread pure-g">
          {this.Title(weekly, this.props.ipuser_list)}
        </div>
      );
    }
  }

  View() {
    if (this.props.weekly_list == "") {
      return (
        <div id="loadingWrap1">
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
        </div>
      );
    }

    const that = this;
    return this.props.weekly_list.map(function (weekly, index) {
      return (
        <a
          href="#"
          onClick={that.props.app.WeeklyListPop.bind(that.props.app, weekly.id)}
        >
          {that.Item(weekly)}
        </a>
      );
    });
  }

  render() {
    return (
      <div id="list" className="pure-u-1">
        {this.View()}
      </div>
    );
  }
}

class WeeklyMenuRender extends React.Component {
  constructor(props) {
    super(props);
  }

  Count(count) {
    return <span className="email-count">({count})</span>;
  }

  Suss(weekly_max_num) {
    if (weekly_max_num == this.props.weeknum_of_year) {
      return <span className="email-label-sussful"></span>;
    }

    return <span className="email-label-faild"></span>;
  }

  Herf(project) {
    return (
      <a
        href="#"
        className="pure-menu-link"
        onClick={this.props.app.WeeklyMenuPop.bind(this.props.app, project.id)}
      >
        &nbsp;&nbsp;
        {this.Suss(this.props.weekly_max_num_list[project.id])}
        {project.title}
        {this.Count(this.props.weekly_count_list[project.id])}
      </a>
    );
  }

  Li(project) {
    if (project.id == this.props.select_project_id) {
      return (
        <li className="pure-menu-item pure-menu-selected">
          {this.Herf(project)}
        </li>
      );
    } else {
      return <li className="pure-menu-item">{this.Herf(project)}</li>;
    }
  }

  LiList(top_id) {
    const that = this;

    return that.props.project_list.map(function (project, index) {
      if (project.top_id == top_id) {
        return that.Li(project);
      }
    });
  }

  View() {
    const that = this;

    if (that.props.project_list == "") {
      return (
        <div id="loadingWrap1">
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
        </div>
      );
    }

    return that.props.project_list.map(function (project, index) {
      if (project.top_id == "0") {
        return (
          <div>
            <li className="pure-menu-heading">{project.title}</li>
            {that.LiList(project.id)}
          </div>
        );
      }
    });
  }

  render() {
    return (
      <div id="nav" className="pure-u">
        <div className="nav-inner">
          <div className="pure-menu">
            <ul className="pure-menu-list">{this.View()}</ul>
          </div>
        </div>
      </div>
    );
  }
}

class APP extends React.Component {
  constructor(props) {
    super(props);
    var websocket_server =
      "ws://" +
      document.location.hostname +
      ":" +
      (parseInt(location.port) + 1) +
      "/ws";

    this.state = {
      project_list: [],
      weekly_count_list: [],
      weekly_max_num_list: [],
      weekly_list: [],
      weekly: [],
      ipuser_list: [],
      weekly_editing: false,
      wait_for_weekly: false,
      weeknum_of_year: "",
      sysconfig: [],
      select_project_id: localStorage.getItem("select_project_id"),
      select_weekly_id: localStorage.getItem("select_weekly_id"),
      ws: new WebSocket(websocket_server)
    };
  }

  componentDidMount() {
    const that = this;

    that.state.ws.onopen = function (event) {
      that.state.ws.send(
        JSON.stringify({
          action: "get_sysconfig"
        })
      );

      that.state.ws.send(
        JSON.stringify({
          action: "get_table_project"
        })
      );

      const select_project_id = localStorage.getItem("select_project_id");
      if (select_project_id != "") {
        that.state.ws.send(
          JSON.stringify({
            action: "get_table_weekly",
            project_id: select_project_id
          })
        );
      }

      that.state.ws.send(
        JSON.stringify({
          action: "get_ipuser"
        })
      );
    };

    that.state.ws.onmessage = function (event) {
      if (event.data != "iamok") {
        var recv_json = JSON.parse(event.data);
        switch (recv_json.action) {
          case "get_table_project": {
            recv_json.json_value.map(function (project, index) {
              if (project.top_id != "0") {
                that.state.ws.send(
                  JSON.stringify({
                    action: "get_max_weeklynum",
                    project_id: project.id.toString()
                  })
                );

                that.state.ws.send(
                  JSON.stringify({
                    action: "get_weekly_count",
                    project_id: project.id.toString()
                  })
                );
              }
            });

            that.setState({
              project_list: recv_json.json_value
            });

            break;
          }

          case "get_table_weekly": {
            const weekly_list = recv_json.json_value;
            const weekly = weekly_list[0];
            localStorage.setItem("select_weekly_id", weekly.id);
            that.setState({
              weekly_list: weekly_list,
              weekly: weekly,
              select_weekly_id: weekly.id
            });

            break;
          }

          case "get_max_weeklynum": {
            var maxNum = recv_json.json_value.map(function (t, i) {
              return t["max(weeknum)"];
            });
            var weekly_max_num_list = that.state.weekly_max_num_list;
            weekly_max_num_list[recv_json.project_id] = maxNum;

            that.setState({
              weekly_max_num_list: weekly_max_num_list
            });

            break;
          }

          case "get_weekly_count": {
            var weeklyCount = recv_json.json_value.map(function (t, i) {
              return t["count(*)"];
            });
            var weekly_count_list = that.state.weekly_count_list;
            weekly_count_list[recv_json.project_id] = weeklyCount;

            that.setState({
              weekly_count_list: weekly_count_list
            });

            break;
          }

          case "get_ipuser": {
            that.setState({
              ipuser_list: recv_json.json_value
            });

            break;
          }

          case "up_weekly": {
            var weekly_list = recv_json.json_value;

            weekly_list.map(function (t, i) {
              var weekly =
                t.id == that.state.select_weekly_id ? t : that.state.weekly;

              that.setState({
                weekly_editing: false,
                wait_for_weekly: false,
                weekly_list: weekly_list,
                weekly: weekly
              });
            });

            return;
          }

          case "add_weekly": {
            const weekly_list = recv_json.json_value;
            const weekly = weekly_list[0];
            localStorage.setItem("select_weekly_id", weekly.id);

            that.state.ws.send(
              JSON.stringify({
                action: "get_max_weeklynum",
                project_id: weekly.project_id.toString()
              })
            );

            that.state.ws.send(
              JSON.stringify({
                action: "get_weekly_count",
                project_id: weekly.project_id.toString()
              })
            );

            that.setState({
              weekly_list: weekly_list,
              weekly: weekly,
              select_weekly_id: weekly.id,
              weekly_editing: false,
              wait_for_weekly: false
            });

            break;
          }

          case "get_sysconfig": {
            const sysconfig = recv_json.json_value;
            sysconfig.map(function (t, i) {
              if (t.key == "weeknum") {
                that.setState({
                  sysconfig: sysconfig,
                  weeknum_of_year: t.value
                });
              }
            });

            break;
          }
        }
      }
    };

    that.state.ws.onclose = function (event) {
      alert(
        "已经与服务器断开连接,请刷新页面!\r\n当前连接状态：" + that.readyState
      );
    };

    that.state.ws.onerror = function (event) {
      alert("WebSocket异常,请刷新页面！");
    };
  }

  WeeklyContentAddPop(e) {
    e.preventDefault();

    this.setState({
      weekly: {
        id: this.state.weekly.id,
        project_id: this.state.weekly.project_id,
        weeknum: this.state.weeknum_of_year,
        body: "",
        ip: "",
        updatetime: ""
      },
      weekly_editing: true,
      select_weekly_id: ""
    });
  }

  WeeklyContentSendPop(weekly, value, e) {
    e.preventDefault();

    this.state.ws.send(
      JSON.stringify({
        action: this.state.select_weekly_id == "" ? "add_weekly" : "up_weekly",
        json_value: {
          id: this.state.select_weekly_id == "" ? "0" : weekly.id.toString(),
          project_id: weekly.project_id.toString(),
          weeknum: weekly.weeknum.toString(),
          body: value
        }
      })
    );

    this.setState({
      wait_for_weekly: true
    });
  }

  WeeklyContentCenterPop(e) {
    e.preventDefault();

    const that = this;
    const select_weekly_id = localStorage.getItem("select_weekly_id");

    that.state.weekly_list.map(function (weekly, index) {
      if (weekly.id == select_weekly_id) {
        that.setState({
          weekly: weekly,
          weekly_editing: false,
          select_weekly_id: select_weekly_id
        });
      }
    });
  }

  WeeklyContentEditPop(weekly, value, e) {
    //事件对象e要放在最后
    e.preventDefault();

    this.setState({
      weekly_editing: true
    });
  }

  WeeklyListPop(select_weekly_id, e) {
    //事件对象e要放在最后
    e.preventDefault();

    const that = this;
    that.state.weekly_list.map(function (weekly, index) {
      if (weekly.id == select_weekly_id) {
        localStorage.setItem("select_weekly_id", select_weekly_id);
        that.setState({
          wait_for_weekly: false,
          weekly_editing: false,
          select_weekly_id: select_weekly_id,
          weekly: weekly
        });
      }
    });
  }

  WeeklyMenuPop(select_project_id, e) {
    //事件对象e要放在最后
    e.preventDefault();
    const old_select_project_id = localStorage.getItem("select_project_id");
    if (old_select_project_id != select_project_id) {
      localStorage.setItem("select_project_id", select_project_id);

      this.state.ws.send(
        JSON.stringify({
          action: "get_table_weekly",
          project_id: select_project_id.toString()
        })
      );

      this.setState({
        wait_for_weekly: false,
        weekly_editing: false,
        select_project_id: select_project_id,
        weekly_list: [],
        weekly: []
      });
    }
  }

  render() {
    return (
      <div id="layout" class="content pure-g">
        <WeeklyMenuRender
          app={this}
          project_list={this.state.project_list}
          select_project_id={this.state.select_project_id}
          weekly_count_list={this.state.weekly_count_list}
          weekly_max_num_list={this.state.weekly_max_num_list}
          weeknum_of_year={this.state.weeknum_of_year}
        />

        <WeeklyListRender
          app={this}
          weekly_list={this.state.weekly_list}
          ipuser_list={this.state.ipuser_list}
          select_weekly_id={this.state.select_weekly_id}
        />

        <WeeklyContentRender
          app={this}
          weekly={this.state.weekly}
          weekly_editing={this.state.weekly_editing}
          ipuser_list={this.state.ipuser_list}
          weekly_max_num={
            this.state.weekly_max_num_list[this.state.weekly.project_id]
          }
          wait_for_weekly={this.state.wait_for_weekly}
          weeknum_of_year={this.state.weeknum_of_year}
        />
      </div>
    );
  }
}

ReactDOM.render(<APP />, document.getElementById("APP"));
